<template>
  <div style="padding: 20px;">
    <!-- 统计信息 -->
    <el-card class="stats-card">
      <div slot="header" class="clearfix">
        <span>成绩统计</span>
      </div>
      <div class="stat-item">
        <span>平均分:</span>
        <strong>{{ averageScore }}</strong>
      </div>
      <div class="stat-item">
        <span>最高分:</span>
        <strong>{{ highestScore.score }} ({{ highestScore.cname }})</strong>
      </div>
      <div class="stat-item">
        <span>最低分:</span>
        <strong>{{ lowestScore.score }} ({{ lowestScore.cname }})</strong>
      </div>
    </el-card>

    <!-- 成绩表格 -->
    <el-table class="currentTable" :data="scs" :header-cell-style="{ background: '#f6f9fa'}" style="margin-top: 20px;">
      <el-table-column prop="cno" label="课程号"></el-table-column>
      <el-table-column prop="cname" label="课程名"></el-table-column>
      <el-table-column prop="score" label="成绩"></el-table-column>
    </el-table>
  </div>
</template>
<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';

const route = useRoute();
const id = route.query.id;
const scs = ref([]);

onMounted(() => {
  getData();
});

const getData = async () => {
  try {
    const response = await axios.get('http://localhost:8080/getMySC', {
      params: {
        id: id
      }
    });
    scs.value = response.data;
    console.log(scs.value);
  } catch (error) {
    console.error(error);
  }
};

// 计算平均分
const averageScore = computed(() => {
  if (!scs.value.length) return 0;
  const total = scs.value.reduce((sum, item) => sum + parseFloat(item.score), 0);
  return (total / scs.value.length).toFixed(2);
});

// 计算最高分及其对应的课程信息
const highestScore = computed(() => {
  if (!scs.value.length) return { score: 0, cname: '' };
  let maxItem = scs.value[0];
  for (let i = 1; i < scs.value.length; i++) {
    if (parseFloat(scs.value[i].score) > parseFloat(maxItem.score)) {
      maxItem = scs.value[i];
    }
  }
  return maxItem;
});

// 计算最低分及其对应的课程信息
const lowestScore = computed(() => {
  if (!scs.value.length) return { score: 0, cname: '' };
  let minItem = scs.value[0];
  for (let i = 1; i < scs.value.length; i++) {
    if (parseFloat(scs.value[i].score) < parseFloat(minItem.score)) {
      minItem = scs.value[i];
    }
  }
  return minItem;
});
</script>
<style scoped>
.stats-card {
  margin-bottom: 20px;
}

.stats-card .stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 16px;
}

.stats-card .stat-item strong {
  font-size: 18px;
  color: #409eff;
}

.currentTable {
  width: 100%;
  border-radius: 8px;
  overflow: hidden;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style>